package com.mrjoew.weekend;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mrjoew.weekend.entities.CgnStaff;
import com.mrjoew.weekend.repositories.CgnStaffRepository;
import com.mrjoew.weekend.repositories.sys.SysLogRepository;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Christopher Jones
 * @explain
 * @since 2020/11/28 0028 17:59
 */
@SpringJUnitConfig
@SpringBootTest(classes = WeekendApplication.class)
public class CgnStaffImportExecutor {

    @Autowired
    private CgnStaffRepository repository;

    @Autowired
    private SysLogRepository sysLogRepository;

    private final String ORIGIN_FILE_PATH = "C:\\Users\\Christopher Jones\\Documents\\Document\\Technology\\Java\\hdfr\\databases\\cud_outside\\cgn staff-list";

    private final String LOG_OUTPUT_PATH = "C:\\Users\\Christopher Jones\\Documents\\Document\\Technology\\Java\\hdfr\\databases\\cud_outside\\cgn staff-list\\log";

    private File logFile;

    @BeforeEach
    public void before() {
        // logFile = new File(LOG_OUTPUT_PATH);
    }

    private void log() {

    }

    @Test
    public void 导入() {
        File originFilePath = new File(this.ORIGIN_FILE_PATH);

        File[] files = originFilePath.listFiles();

        if (ArrayUtils.isEmpty(files)) {
            return;
        }

        // 遍历 json 文件
        for (File file : files) {
            if (file.isFile())
                try (FileInputStream fis = new FileInputStream(file)) {
                    final BufferedInputStream bis = new BufferedInputStream(fis);
                    byte[] bytes = new byte[bis.available()];

                    bis.read(bytes);

                    List<CgnStaff> cgnStaffs = new ArrayList<>();

                    final JSONArray array = (JSONArray) JSONObject.parse(new String(bytes));
                    array.forEach(a -> {
                        cgnStaffs.add(JSONObject.parseObject(a.toString(), CgnStaff.class));
                    });

                    repository.saveAll(cgnStaffs);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}
